package com.xyht.sca_s.student_manage_system.modules.clockIn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.SmsClockInClassesSetting;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.SmsClockInGpsSetting;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.SmsClockInGroupSetting;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.SmsClockInGroupUserRelation;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.req.*;
import com.xyht.sca_s.student_manage_system.modules.clockIn.entity.resp.*;
import com.xyht.sca_s.student_manage_system.modules.clockIn.mapper.SmsClockInClassesSettingMapper;
import com.xyht.sca_s.student_manage_system.modules.clockIn.mapper.SmsClockInGpsSettingMapper;
import com.xyht.sca_s.student_manage_system.modules.clockIn.mapper.SmsClockInGroupSettingMapper;
import com.xyht.sca_s.student_manage_system.modules.clockIn.mapper.SmsClockInGroupUserRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.clockIn.service.SmsClockInGroupSettingService;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.clockIn.constant.ClockInObjectTypeConstant.CLOCK_IN_OBJECT_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.clockIn.constant.ClockInObjectTypeConstant.CLOCK_IN_OBJECT_TYPE_ROLE;


/**
 * <p>
 * 考勤组设置表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-08-03
 */
@Service
public class SmsClockInGroupSettingServiceImpl extends ServiceImpl<SmsClockInGroupSettingMapper, SmsClockInGroupSetting> implements SmsClockInGroupSettingService {

    @Resource
    private SmsClockInGroupSettingMapper groupSettingMapper;
    @Resource
    private SmsClockInGpsSettingMapper gpsSettingMapper;
    @Resource
    private SmsClockInClassesSettingMapper classesSettingMapper;
    @Resource
    private CacheUtil cacheUtil;
    @Resource
    private SmsRoleMapper smsRoleMapper;
    @Resource
    private SmsUserRoleRelationMapper userRoleRelationMapper;
    @Resource
    private SmsClockInGroupUserRelationMapper groupUserRelationMapper;


    @Override
    public ResponseResult addObjectId(SmsClockInObjectIdAddReq addReq) {


        SmsClockInUserInfoAndStateResp smsClockInObjectIdAndStateResp = new SmsClockInUserInfoAndStateResp();
        List<SmsClockInUserInfoListResp> userInfoList = new ArrayList<>();

        if(addReq.getObjectIdList() == null || addReq.getObjectIdList().size() < 1){
            return CommonResult.success(smsClockInObjectIdAndStateResp);
        }
        List<String> objectIdList = addReq.getObjectIdList();
        //查看详情页修改时
        if(!isNullOrEmpty(addReq.getClockInGroupId())){
            List<SmsClockInGroupUserRelation> collect = groupUserRelationMapper.selectList(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
                    .eq(SmsClockInGroupUserRelation::getClockInGroupId, addReq.getClockInGroupId()));
            if(!collect.isEmpty()){
                for (SmsClockInGroupUserRelation groupUserRelation : collect) {
                    objectIdList.remove(groupUserRelation.getUserId());
                }
            }
            if (objectIdList.size() > 0) {
                for (String objectId : objectIdList) {
                    SmsClockInUserInfoListResp userInfoResp = new SmsClockInUserInfoListResp();
                    SmsClockInGroupSetting clockInGroupSetting = groupSettingMapper.selectById(addReq.getClockInGroupId());
                    if (!isNullOrEmpty(clockInGroupSetting)) {
                        userInfoResp.setClockInGroupName(clockInGroupSetting.getClockInGroupName());
                        userInfoResp.setClockInGroupId(clockInGroupSetting.getId());
                    }
                    SmsClockInUserResp clockInUserResp = new SmsClockInUserResp();
                    SmsUser userInfo = cacheUtil.getUserInfo(objectId);
                    if (userInfo != null) {
                        BeanUtils.copyProperties(userInfo, clockInUserResp);
                        userInfoResp.setUserInfo(clockInUserResp);
                    }
                    userInfoList.add(userInfoResp);
                }
                smsClockInObjectIdAndStateResp.setList(userInfoList);
            }
        }else {

            //校验参加考勤的部门和人员是否设置
            List<SmsClockInGroupUserRelation> groupUserRelations = groupUserRelationMapper.selectList(null)
                    .stream()
                    .filter(groupUserRelation -> {
                        String userRelationUserId = groupUserRelation.getUserId();
                        if (objectIdList.contains(userRelationUserId)) {
                            return true;
                        }
                        return false;
                    })
                    .collect(Collectors.toList());
            if (groupUserRelations.size() > 0) {
                for (SmsClockInGroupUserRelation groupUserRelation : groupUserRelations) {
                    SmsClockInUserInfoListResp userInfoResp = new SmsClockInUserInfoListResp();
                    SmsClockInGroupSetting clockInGroupSetting = groupSettingMapper.selectById(groupUserRelation.getClockInGroupId());
                    if (!isNullOrEmpty(clockInGroupSetting)) {
                        userInfoResp.setClockInGroupName(clockInGroupSetting.getClockInGroupName());
                        userInfoResp.setClockInGroupId(clockInGroupSetting.getId());
                    }
                    SmsClockInUserResp clockInUserResp = new SmsClockInUserResp();
                    SmsUser userInfo = cacheUtil.getUserInfo(groupUserRelation.getUserId());
                    if (userInfo != null) {
                        BeanUtils.copyProperties(userInfo, clockInUserResp);
                        userInfoResp.setUserInfo(clockInUserResp);
                    }
                    userInfoList.add(userInfoResp);
                }

            }
            smsClockInObjectIdAndStateResp.setList(userInfoList);
        }

        return CommonResult.success(smsClockInObjectIdAndStateResp);
    }

    @Override
    @Transactional
    public ResponseResult addClockInGroupSetting(String userId, SmsClockInGroupSettingAddReq addReq) {

        if (isNullOrEmpty(addReq.getClockInGroupName()) || isNullOrEmpty(addReq.getIsAllowClockIn())
                || isNullOrEmpty(addReq.getRepairTime()) || isNullOrEmpty(addReq.getRepairTimes())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验参加考勤的部门和人员是否设置
        if(addReq.getClockInObjectIdList() == null || addReq.getClockInObjectIdList().size() < 1){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验是否允许打卡
        if(addReq.getIsAllowClockIn()){
            if(addReq.getRepairTypeList() == null || addReq.getRepairTypeList().size() < 1){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //校验是否限制补卡次数
        if(addReq.getIsRepairTime()){
            if(isNullOrEmpty(addReq.getRepairTime())){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //校验是否限制补卡时间
        if(addReq.getIsRepairTimes()){
            if(isNullOrEmpty(addReq.getRepairTimes())){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //校验审批人
        if(addReq.getIsAllow() && addReq.getAllowUserType() != null) {
            if (addReq.getAllowUserIdList() == null || addReq.getAllowUserIdList().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.CLOCK_IN__ALLOW_USER_NOT_SETTING);
            }
        }
        //校验班次是否设置
        if (addReq.getClassesSettingAddList() == null || addReq.getClassesSettingAddList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_CLASSES_NOT_SETTING);
        }
        for (SmsClockInClassesSettingAddReq classesSettingAddReq : addReq.getClassesSettingAddList()) {
            if(classesSettingAddReq.getLatestTimeLimit() == null){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        //校验GPS是否设置
        if(addReq.getGpsSettingAddList() == null || addReq.getGpsSettingAddList().size() < 1){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GPS_NOT_SETTING);
        }

        //创建考勤组设置表
        SmsClockInGroupSetting addClockInGroupSetting = new SmsClockInGroupSetting();
        BeanUtils.copyProperties(addReq,addClockInGroupSetting);
//        addClockInGroupSetting.setClockInObjectId(addReq.getClockInObjectIdList().toString());
        addClockInGroupSetting.setRepairType(addReq.getRepairTypeList().toString());
        addClockInGroupSetting.setAllowUserId(addReq.getAllowUserIdList().toString());
        addClockInGroupSetting.setUserId(userId);
        addClockInGroupSetting.setUpdateObjectIdTime(new Date());
        groupSettingMapper.insert(addClockInGroupSetting);

        //考勤组id
        String groupSettingId = addClockInGroupSetting.getId();
        List<String> objectIdList = addReq.getClockInObjectIdList();
        List<SmsClockInGroupUserRelation> groupUserRelations = groupUserRelationMapper.selectList(null)
                .stream()
                .filter(groupUserRelation -> {
                    String userRelationUserId = groupUserRelation.getUserId();
                    if (objectIdList.contains(userRelationUserId)) {
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
        //判断是否存在其他考勤组内
        if(groupUserRelations.size() > 0){
            for (SmsClockInGroupUserRelation groupUserRelation : groupUserRelations) {
                //移除原考勤组的人
                groupUserRelationMapper.delete(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
                .eq(SmsClockInGroupUserRelation::getClockInGroupId,groupUserRelation.getClockInGroupId())
                .eq(SmsClockInGroupUserRelation::getUserId,groupUserRelation.getUserId()));
            }
        }
        //创建考勤组和需要考勤人关系表
        for (String objectId : objectIdList) {
            SmsClockInGroupUserRelation groupUserRelation = new SmsClockInGroupUserRelation();
            groupUserRelation.setClockInGroupId(groupSettingId);
            groupUserRelation.setUserId(objectId);
            groupUserRelationMapper.insert(groupUserRelation);
        }

        //创建班次设置表
        List<SmsClockInClassesSettingAddReq> classesSettingAddList = addReq.getClassesSettingAddList();
        Date date = new Date();
        date.setHours(23);
        date.setMinutes(55);
        date.setSeconds(0);
        for (SmsClockInClassesSettingAddReq classesSettingAddReq : classesSettingAddList) {
            SmsClockInClassesSetting addClassesSetting = new SmsClockInClassesSetting();
            long differenceMil = getDifferenceMin(date, TimeUtil.TimeFormat(classesSettingAddReq.getEndHours()));
            long nm = 1000 * 60;
            int differenceMin = (int) (differenceMil / nm);
            if (!isNullOrEmpty(classesSettingAddReq.getLatestTimeLimit())) {
                if (differenceMin < classesSettingAddReq.getLatestTimeLimit()) {
                    return CommonResult.failed(CommonCodeEnum.CLOCK_IN_END_LATEST_OVER);
                }
            }
            BeanUtils.copyProperties(classesSettingAddReq, addClassesSetting);
            addClassesSetting.setStartHours(TimeUtil.TimeFormat(classesSettingAddReq.getStartHours()));
            addClassesSetting.setEndHours(TimeUtil.TimeFormat(classesSettingAddReq.getEndHours()));
            addClassesSetting.setClockInGroupId(groupSettingId);
            classesSettingMapper.insert(addClassesSetting);
        }

        //创建GPS设置表
        List<SmsClockInGpsSettingAddReq> gpsSettingAddList = addReq.getGpsSettingAddList();
        for (SmsClockInGpsSettingAddReq gpsSettingAddReq : gpsSettingAddList) {
            SmsClockInGpsSetting addGpsSetting = new SmsClockInGpsSetting();
            BeanUtils.copyProperties(gpsSettingAddReq,addGpsSetting);
            addGpsSetting.setClockInGroupId(groupSettingId);
            gpsSettingMapper.insert(addGpsSetting);
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult getGroupList(Integer pageNum, Integer pageSize) {
        Page<SmsClockInGroupSetting> page = new Page<>(pageNum,pageSize);
        List<SmsClockInGroupSettingListResp> groupSettingList = new ArrayList<>();
        LambdaQueryWrapper<SmsClockInGroupSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(SmsClockInGroupSetting::getCreateTime);

        List<SmsClockInGroupSetting> groupSettingList1 = groupSettingMapper.selectList(queryWrapper);
        if(groupSettingList1 == null){
            return CommonResult.success(groupSettingList);
        }
//        SmsClockInGroupSetting clockInGroupSetting = groupSettingList1.get(0);
        groupSettingMapper.selectPage(page,queryWrapper);


        List<SmsClockInGroupSetting> records = page.getRecords();
        int n = 0;
        if(records !=null && records.size() > 0) {
            for (int i = 0; i < records.size(); i++) {
                SmsClockInGroupSettingListResp groupSettingResp = new SmsClockInGroupSettingListResp();
                BeanUtils.copyProperties(records.get(i), groupSettingResp);
                groupSettingResp.setClockInCount(n);
//                List<String> objectIdList = JSONObject.parseArray(records.get(i).getClockInObjectId(), String.class);
//                groupSettingResp.setClockInObjectIdList(objectIdList);//需要考勤的id
                List<Integer> repairTypeList = JSONObject.parseArray(records.get(i).getRepairType(), Integer.class);
                groupSettingResp.setRepairTypeList(repairTypeList);//补卡类型
//                if(records.get(i).getUpdateObjectIdTime().compareTo(clockInGroupSetting.getUpdateObjectIdTime()) == 0) {
//                    groupSettingResp.setIsUse(1);//已启用
//                }else {
//                    groupSettingResp.setIsUse(0);//未启用
//                }
                //GPS信息
                List<SmsClockInGpsSettingResp> gpsSettingResps = gpsSettingMapper.selectList(new LambdaQueryWrapper<SmsClockInGpsSetting>()
                        .eq(SmsClockInGpsSetting::getClockInGroupId, records.get(i).getId()))
                        .stream()
                        .map(gps -> {
                            SmsClockInGpsSettingResp gpsSettingResp = new SmsClockInGpsSettingResp();
                            BeanUtils.copyProperties(gps, gpsSettingResp);
                            return gpsSettingResp;
                        })
                        .collect(Collectors.toList());
                groupSettingResp.setGpsSettingDetailList(gpsSettingResps);
                //班次信息
                List<SmsClockInClassesSettingResp> classesSettingResps = classesSettingMapper.selectList(new LambdaQueryWrapper<SmsClockInClassesSetting>()
                        .eq(SmsClockInClassesSetting::getClockInGroupId, records.get(i).getId())
                        .eq(SmsClockInClassesSetting::getIsUse, true))
                        .stream()
                        .map(classesSetting -> {
                            SmsClockInClassesSettingResp classesSettingResp = new SmsClockInClassesSettingResp();
                            BeanUtils.copyProperties(classesSetting, classesSettingResp);
                            classesSettingResp.setStartHours(TimeUtil.TimeFormatSting(classesSetting.getStartHours()));//上班时间
                            classesSettingResp.setEndHours(TimeUtil.TimeFormatSting(classesSetting.getEndHours()));//下班时间
                            return classesSettingResp;
                        })
                        .collect(Collectors.toList());
                groupSettingResp.setClassesSettingDetailList(classesSettingResps);
                groupSettingList.add(groupSettingResp);
            }

        }
        int total = (int)page.getTotal();
        return CommonResult.success(groupSettingList,total);
    }

    private long getDifferenceMin(Date clockInHours,Date limitDate) {
        //打卡时的年月日转为一致,方便对比
        clockInHours.setYear(limitDate.getYear());
        clockInHours.setMonth(limitDate.getMonth());
        clockInHours.setDate(limitDate.getDate());
        long nowMil = clockInHours.getTime();
        long limitMil = limitDate.getTime();
        //毫秒差
        return nowMil - limitMil;
    }
    @Override
    public ResponseResult getGroupSettingDetail(String userId, String groupId) {
        if(isNullOrEmpty(groupId)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验考勤组基本信息
        SmsClockInGroupSetting groupSetting = groupSettingMapper.selectById(groupId);
        if(groupSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GROUP_NOT_EXIST);
        }
        //校验班次设置
        List<SmsClockInClassesSetting> classesSettings = classesSettingMapper.selectList(new LambdaQueryWrapper<SmsClockInClassesSetting>()
                .eq(SmsClockInClassesSetting::getClockInGroupId, groupId));
        if(classesSettings == null || classesSettings.size() < 1){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_CLASSES_NOT_EXIST);
        }
        //校验GPS考勤方式
        List<SmsClockInGpsSetting> gpsSettings = gpsSettingMapper.selectList(new LambdaQueryWrapper<SmsClockInGpsSetting>()
                .eq(SmsClockInGpsSetting::getClockInGroupId, groupId));
        if(gpsSettings == null || gpsSettings.size() < 1){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GPS_NOT_SETTING);
        }
        SmsClockInGroupSettingDetailResp groupSettingDetailResp = new SmsClockInGroupSettingDetailResp();
        List<SmsClockInClassesSettingResp> classesSettingList;
        List<SmsClockInGpsSettingResp> gpsSettingList;
        //考勤基本信息赋值
        BeanUtils.copyProperties(groupSetting,groupSettingDetailResp);
        //审批人
        List<String> allowUserIdList = JSONObject.parseArray(groupSetting.getAllowUserId(), String.class);
        List<SmsClockInUserResp> allowUserInfoList = new ArrayList<>();
        for (String allowUserId : allowUserIdList) {
            if (groupSetting.getAllowUserType() == CLOCK_IN_OBJECT_TYPE_ROLE) {
                SmsRole smsRole = smsRoleMapper.selectById(allowUserId);
                SmsClockInUserResp userResp = new SmsClockInUserResp();
                if(smsRole != null) {
                    userResp.setId(allowUserId);
                    userResp.setRealName(smsRole.getRoleName());//审批角色
                }
                allowUserInfoList.add(userResp);
            } else if (groupSetting.getAllowUserType() == CLOCK_IN_OBJECT_TYPE_PERSON) {
                SmsClockInUserResp userResp = new SmsClockInUserResp();
                SmsUser userInfo = cacheUtil.getUserInfo(allowUserId);
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, userResp);
                }
                allowUserInfoList.add(userResp);
            }
        }
        groupSettingDetailResp.setAllowUserInfoList(allowUserInfoList);//审批人
        //需要考勤的人或角色
        List<SmsClockInUserResp> clockInObjectInfoList = new ArrayList<>();
        clockInObjectInfoList = groupUserRelationMapper.selectList(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
        .eq(SmsClockInGroupUserRelation::getClockInGroupId,groupId))
                .stream()
                .map(groupUserRelation -> {
                    SmsClockInUserResp clockInUserResp = new SmsClockInUserResp();
                    SmsUser userInfo = cacheUtil.getUserInfo(groupUserRelation.getUserId());
                    if (userInfo != null) {
                        BeanUtils.copyProperties(userInfo, clockInUserResp);
                    }
                    return clockInUserResp;
                })
                .collect(Collectors.toList());
//        List<String> objectIdList = JSONObject.parseArray(groupSetting.getClockInObjectId(), String.class);
//        for (String objectId : objectIdList) {
//            if (groupSetting.getClockInObjectType() == CLOCK_IN_OBJECT_TYPE_ROLE) {
//                SmsRole smsRole = smsRoleMapper.selectById(objectId);
//                SmsClockInUserResp clockInUserResp = new SmsClockInUserResp();
//                if(smsRole != null) {
//                    clockInUserResp.setId(objectId);
//                    clockInUserResp.setRealName(smsRole.getRoleName());
//                    clockInObjectInfoList.add(clockInUserResp);//考勤的角色
//                }
//            }else if (groupSetting.getClockInObjectType() == CLOCK_IN_OBJECT_TYPE_PERSON) {
//                SmsClockInUserResp clockInUserResp = new SmsClockInUserResp();
//                SmsUser userInfo = cacheUtil.getUserInfo(objectId);
//                if(userInfo != null){
//                    BeanUtils.copyProperties(userInfo,clockInUserResp);
//                }
//                clockInObjectInfoList.add(clockInUserResp);
//            }
//        }
        groupSettingDetailResp.setClockInObjectInfoList(clockInObjectInfoList);
        List<Integer> repairTypeList = new ArrayList<>();
        if(groupSetting.getIsAllowClockIn()) {
            repairTypeList = JSONObject.parseArray(groupSetting.getRepairType(), Integer.class);
            groupSettingDetailResp.setRepairTypeList(repairTypeList);
        }else {
            groupSettingDetailResp.setRepairTypeList(repairTypeList);
        }
        //班次信息赋值
        classesSettingList = classesSettings
                .stream()
                .map(classesSetting -> {
                    SmsClockInClassesSettingResp classesSettingDetailResp = new SmsClockInClassesSettingResp();
                    BeanUtils.copyProperties(classesSetting, classesSettingDetailResp);
                    classesSettingDetailResp.setStartHours(TimeUtil.TimeFormatSting(classesSetting.getStartHours()));
                    classesSettingDetailResp.setEndHours(TimeUtil.TimeFormatSting(classesSetting.getEndHours()));
                    return classesSettingDetailResp;
                })
                .collect(Collectors.toList());
        groupSettingDetailResp.setClassesSettingDetailList(classesSettingList);
        //GPS考勤方式赋值
        gpsSettingList = gpsSettings
                .stream()
                .map(gpdSetting ->{
                    SmsClockInGpsSettingResp gpsSettingDetailResp = new SmsClockInGpsSettingResp();
                    BeanUtils.copyProperties(gpdSetting,gpsSettingDetailResp);
                    return gpsSettingDetailResp;
                })
                .collect(Collectors.toList());
        groupSettingDetailResp.setGpsSettingDetailList(gpsSettingList);

        return CommonResult.success(groupSettingDetailResp);
    }

    @Override
    @Transactional
    public ResponseResult updateGroupSetting(String userId, SmsClockInGroupSettingUpdateReq groupSettingUpdateReq) {
        if(isNullOrEmpty(groupSettingUpdateReq.getId())){
            return CommonResult.success(CommonCodeEnum.INVALID_PARAM);
        }
        //校验考勤组基本信息
        SmsClockInGroupSetting groupSetting = groupSettingMapper.selectById(groupSettingUpdateReq.getId());
        if(groupSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GROUP_NOT_EXIST);
        }
        BeanUtils.copyProperties(groupSettingUpdateReq,groupSetting);
        //校验参加考勤的部门和人员是否设置
        if(groupSettingUpdateReq.getClockInObjectIdList() == null || groupSettingUpdateReq.getClockInObjectIdList().size() < 1){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验是否允许打卡
        if(groupSettingUpdateReq.getIsAllowClockIn()){
            if(groupSettingUpdateReq.getRepairTypeList() == null || groupSettingUpdateReq.getRepairTypeList().size() < 1){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }else {
            groupSetting.setRepairType(new ArrayList<>().toString());
            groupSetting.setIsRepairTime(false);
            groupSetting.setRepairTime(0);
            groupSetting.setIsRepairTimes(false);
            groupSetting.setRepairTimes(0);
        }

        //校验是否限制补卡次数
        if(groupSettingUpdateReq.getIsRepairTime()){
            if(isNullOrEmpty(groupSettingUpdateReq.getRepairTime())){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }else {
            groupSetting.setRepairTime(0);
        }

        //校验是否限制补卡时间
        if(groupSettingUpdateReq.getIsRepairTimes()){
            if(isNullOrEmpty(groupSettingUpdateReq.getRepairTimes())){
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }else {
            groupSetting.setRepairTimes(0);
        }
        //校验审批人
        if(groupSettingUpdateReq.getIsAllow() && groupSettingUpdateReq.getAllowUserType() != null) {
            if (groupSettingUpdateReq.getAllowUserIdList() == null || groupSettingUpdateReq.getAllowUserIdList().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.CLOCK_IN__ALLOW_USER_NOT_SETTING);
            }
        }
        if(groupSettingUpdateReq.getIsAllow()){
            groupSetting.setAllowUserId(groupSettingUpdateReq.getAllowUserIdList().toString());
//            //修改考勤流程对象类型
//            List<String> list = JSONObject.parseArray(groupSetting.getClockInObjectId(), String.class);
//            if(CollectionUtils.disjunction(list,groupSettingUpdateReq.getClockInObjectIdList()).size() != 0){
//                groupSetting.setUpdateObjectIdTime(new Date());
//            }
//            //参加考勤流程对象类型
//            groupSetting.setClockInObjectId(groupSettingUpdateReq.getClockInObjectIdList().toString());
        }
        List<String> objectIdList = groupSettingUpdateReq.getClockInObjectIdList();
        List<SmsClockInGroupUserRelation> groupUserRelations = groupUserRelationMapper.selectList(null)
                .stream()
                .filter(groupUserRelation -> {
                    String userRelationUserId = groupUserRelation.getUserId();
                    if (objectIdList.contains(userRelationUserId)) {
                        return true;
                    }
                    return false;
                })
                .collect(Collectors.toList());
        //判断是否存在其他考勤组内
        if(groupUserRelations.size() > 0){
            for (SmsClockInGroupUserRelation groupUserRelation : groupUserRelations) {
                //移除原考勤组的人
                groupUserRelationMapper.delete(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
                        .eq(SmsClockInGroupUserRelation::getClockInGroupId,groupUserRelation.getClockInGroupId())
                        .eq(SmsClockInGroupUserRelation::getUserId,groupUserRelation.getUserId()));
            }
        }
        //考勤人员 先删除再新增
        groupUserRelationMapper.delete(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
        .eq(SmsClockInGroupUserRelation::getClockInGroupId,groupSettingUpdateReq.getId()));
        List<String> clockInObjectIdList = groupSettingUpdateReq.getClockInObjectIdList();
        for (String objectId : clockInObjectIdList) {
            SmsClockInGroupUserRelation groupUserRelation = new SmsClockInGroupUserRelation();
            groupUserRelation.setClockInGroupId(groupSettingUpdateReq.getId());
            groupUserRelation.setUserId(objectId);
            groupUserRelationMapper.insert(groupUserRelation);
        }
        //允许补卡时,补卡类型
       if(groupSettingUpdateReq.getIsAllowClockIn()){
           groupSetting.setRepairType(groupSettingUpdateReq.getRepairTypeList().toString());
       }

        groupSettingMapper.updateById(groupSetting);
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult deletedClockInGroup(SmsClockInGroupSettingDeletedReq deletedReq) {
        if(isNullOrEmpty(deletedReq.getClockInGroupId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsClockInGroupSetting clockInGroupSetting = groupSettingMapper.selectById(deletedReq.getClockInGroupId());
        if(clockInGroupSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GROUP_NOT_EXIST);
        }
        //删除考勤组
        groupSettingMapper.deleteById(deletedReq.getClockInGroupId());
        //删除班次
        classesSettingMapper.delete(new LambdaQueryWrapper<SmsClockInClassesSetting>()
        .eq(SmsClockInClassesSetting::getClockInGroupId,deletedReq.getClockInGroupId()));
        //删除GPS设置
        gpsSettingMapper.delete(new LambdaQueryWrapper<SmsClockInGpsSetting>()
        .eq(SmsClockInGpsSetting::getClockInGroupId,deletedReq.getClockInGroupId()));
        //删除考勤组和考勤人员关系表
        groupUserRelationMapper.delete(new LambdaQueryWrapper<SmsClockInGroupUserRelation>()
        .eq(SmsClockInGroupUserRelation::getClockInGroupId,deletedReq.getClockInGroupId()));

        return CommonResult.success();
    }


    @Override
    public ResponseResult getClassesSettingId(String classesId,String groupId) {
        if(isNullOrEmpty(classesId) || isNullOrEmpty(groupId)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsClockInClassesSetting classesSetting = classesSettingMapper.selectOne(new LambdaQueryWrapper<SmsClockInClassesSetting>()
                .eq(SmsClockInClassesSetting::getId, classesId)
                .eq(SmsClockInClassesSetting::getClockInGroupId, groupId));
        if(classesSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_CLASSES_NOT_EXIST);
        }
        SmsClockInClassesSettingDetailResp  classesSettingDetailResp = new SmsClockInClassesSettingDetailResp();
        BeanUtils.copyProperties(classesSetting,classesSettingDetailResp);
        classesSettingDetailResp.setClockInGroupId(groupId);//考勤组id
        classesSettingDetailResp.setClassesId(classesId);//班次id
        classesSettingDetailResp.setStartHours(TimeUtil.TimeFormatSting(classesSetting.getStartHours()));//上班时间
        classesSettingDetailResp.setEndHours(TimeUtil.TimeFormatSting(classesSetting.getEndHours()));//下班时间
        return CommonResult.success(classesSettingDetailResp);
    }

    @Override
    public ResponseResult updateClassesSetting(SmsClockInClassesSettingUpdateReq classesUpdateReq) {
        if(isNullOrEmpty(classesUpdateReq.getClassesId()) || isNullOrEmpty(classesUpdateReq.getClockInGroupId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsClockInClassesSetting classesSetting = classesSettingMapper.selectOne(new LambdaQueryWrapper<SmsClockInClassesSetting>()
                .eq(SmsClockInClassesSetting::getClockInGroupId, classesUpdateReq.getClockInGroupId())
                .eq(SmsClockInClassesSetting::getId, classesUpdateReq.getClassesId()));

        if(classesSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_CLASSES_NOT_EXIST);
        }
        //校验最晚下班时间
        Date date = new Date();
        date.setHours(23);
        date.setMinutes(55);
        date.setSeconds(0);
        long differenceMil = getDifferenceMin(date, TimeUtil.TimeFormat(classesUpdateReq.getEndHours()));
        long nm = 1000 * 60;
        int differenceMin = (int) (differenceMil / nm);
        if (!isNullOrEmpty(classesUpdateReq.getLatestTimeLimit())) {
            if (differenceMin < classesUpdateReq.getLatestTimeLimit()) {
                return CommonResult.failed(CommonCodeEnum.CLOCK_IN_END_LATEST_OVER);
            }
        }
        BeanUtils.copyProperties(classesUpdateReq,classesSetting);
        classesSetting.setId(classesUpdateReq.getClassesId());
        classesSetting.setStartHours(TimeUtil.TimeFormat(classesUpdateReq.getStartHours()));//上班时间
        classesSetting.setEndHours(TimeUtil.TimeFormat(classesUpdateReq.getEndHours()));//下班时间
        classesSettingMapper.updateById(classesSetting);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getGpsSettingId(String gpsId,String groupId) {
        if(isNullOrEmpty(gpsId) || isNullOrEmpty(groupId)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsClockInGpsSetting gpsSetting = gpsSettingMapper.selectOne(new LambdaQueryWrapper<SmsClockInGpsSetting>()
                .eq(SmsClockInGpsSetting::getClockInGroupId, groupId)
                .eq(SmsClockInGpsSetting::getId, gpsId));
        if(gpsSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GPS_NOT_EXIST);
        }
        SmsClockInGpsSettingDetailResp gpsSettingResp = new SmsClockInGpsSettingDetailResp();
        BeanUtils.copyProperties(gpsSetting,gpsSettingResp);
        gpsSettingResp.setGpsId(gpsId);
        gpsSettingResp.setClockInGroupId(groupId);
        return CommonResult.success(gpsSettingResp);
    }

    @Override
    public ResponseResult updateGpsSettingId(SmsClockInGpsSettingUpdateReq gpsSettingUpdateReq) {
        if(isNullOrEmpty(gpsSettingUpdateReq.getGpsId()) || isNullOrEmpty(gpsSettingUpdateReq.getClockInGroupId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsClockInGpsSetting gpsSetting = gpsSettingMapper.selectOne(new LambdaQueryWrapper<SmsClockInGpsSetting>()
                .eq(SmsClockInGpsSetting::getId, gpsSettingUpdateReq.getGpsId())
                .eq(SmsClockInGpsSetting::getClockInGroupId, gpsSettingUpdateReq.getClockInGroupId()));
        if(gpsSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GPS_NOT_EXIST);
        }
        BeanUtils.copyProperties(gpsSettingUpdateReq,gpsSetting);
        gpsSetting.setId(gpsSettingUpdateReq.getGpsId());
        gpsSettingMapper.updateById(gpsSetting);
        return CommonResult.success();
    }

    @Override
    public ResponseResult deletedGps(SmsClockInGpsSettingDeletedReq deletedReq) {
        if(isNullOrEmpty(deletedReq.getGpsId()) || isNullOrEmpty(deletedReq.getClockInGroupId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        LambdaQueryWrapper<SmsClockInGpsSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmsClockInGpsSetting::getClockInGroupId, deletedReq.getClockInGroupId())
                .eq(SmsClockInGpsSetting::getId, deletedReq.getGpsId());
        SmsClockInGpsSetting gpsSetting = gpsSettingMapper.selectOne(queryWrapper);
        if(gpsSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GPS_NOT_EXIST);
        }
        gpsSettingMapper.delete(queryWrapper);
        return CommonResult.success();
    }

    @Override
    public ResponseResult useGroupSetting(SmsClockInGroupSettingDeletedReq useGroupSettingId) {
        if(isNullOrEmpty(useGroupSettingId.getClockInGroupId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsClockInGroupSetting clockInGroupSetting = groupSettingMapper.selectById(useGroupSettingId.getClockInGroupId());
        if(clockInGroupSetting == null){
            return CommonResult.failed(CommonCodeEnum.CLOCK_IN_GROUP_NOT_EXIST);
        }
        clockInGroupSetting.setUpdateObjectIdTime(new Date());
        groupSettingMapper.updateById(clockInGroupSetting);
        return CommonResult.success();
    }


}
